﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bot.Application.Dto;
using Bot.Application.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

namespace Bot.WebAPI.Controllers
{
    [Route("api/v3/chatbot/images")]
    [ApiController]
    public class ImagesController : ControllerBase
    {

        private readonly IImageAppService _app;
        public ImagesController(IImageAppService app)
        {
            this._app = app;
        }

        [HttpGet("{id}")]
        public ActionResult Get([FromRoute] Guid id)
        {
            ImageCreateDto dto = _app.Get(id);
            return new FileContentResult(dto.Content, GetContentType(dto.Name));
        }

        [HttpPost]
        public ActionResult<ImageDto> Post([FromForm] IFormCollection formCollection)
        {
            FormFileCollection filelist = (FormFileCollection)formCollection?.Files;
            if (filelist!= null)
            {
                var file = filelist.FirstOrDefault();
                if (file != null)
                {
                    ImageDto image = _app.Add(file);
                    return CreatedAtAction(nameof(Get), new { id = image.Id }, image);
                }
            }
            return BadRequest();
        }

        private MediaTypeHeaderValue GetContentType(string fileName)
        {
            if (fileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || 
                fileName.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase)) 
                return new MediaTypeHeaderValue("image/jpeg");
            if (fileName.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)) 
                return new MediaTypeHeaderValue("image/bmp");
            if (fileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) 
                return new MediaTypeHeaderValue("image/png");
            if (fileName.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)) 
                return new MediaTypeHeaderValue("image/gif");
            return new MediaTypeHeaderValue("application/octet-stream");
        }
    }
}
